package com.jl15988.simpletools.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jl15988.simpletools.system.constant.UserConstant;
import com.jl15988.simpletools.system.domain.entity.User;
import com.jl15988.simpletools.system.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户详情服务实现
 *
 * @author jl15988
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (user == null) {
            log.error("用户不存在: {}", username);
            throw new UsernameNotFoundException("用户不存在");
        }

        // 设置权限
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        // 根据角色设置权限
        switch (user.getRole()) {
            case UserConstant.ROLE_ADMIN:
                // 管理员
                authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
                authorities.add(new SimpleGrantedAuthority("app:review:*"));
                authorities.add(new SimpleGrantedAuthority("user:*:*"));
                break;
            case UserConstant.ROLE_DEVELOPER:
                // 开发者
                authorities.add(new SimpleGrantedAuthority("ROLE_DEVELOPER"));
                authorities.add(new SimpleGrantedAuthority("app:upload:*"));
                authorities.add(new SimpleGrantedAuthority("app:update:own"));
                break;
            case UserConstant.ROLE_USER:
            default:
                // 普通用户
                authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
                break;
        }

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                authorities
        );
    }
} 